package com.burton.dp.listener;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
/**
 * 
 * @author wangshuimin
 * 字节点增删改
 */
public class NodeCacheChildDemo {

	static String path = "/zk1";
	static CuratorFramework client = CuratorFrameworkFactory.builder()
			.connectString("127.0.0.1:2181").sessionTimeoutMs(5000)
			.retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();

	public static void main(String[] args) throws Exception {
		client.start();

		PathChildrenCache cache = new PathChildrenCache(client, path, true);
		cache.start(StartMode.POST_INITIALIZED_EVENT);
		cache.getListenable().addListener(new PathChildrenCacheListener() {
			public void childEvent(CuratorFramework client,
					PathChildrenCacheEvent event) throws Exception {
				switch (event.getType()) {
				case CHILD_ADDED:
					System.out.println("add :path=" + event.getData().getPath()+";data="+new String(event.getData().getData()));
					break;
				case CHILD_UPDATED:
					System.out.println("update :path=" + event.getData().getPath()+";data="+new String(event.getData().getData()));
					break;
				case CHILD_REMOVED:
					System.out.println("remove :path=" + event.getData().getPath()+";data="+new String(event.getData().getData()));
					break;
				default:
					break;
				}
			}
		});
		if (client.checkExists().forPath(path) == null) {
			client.create().creatingParentsIfNeeded()
					.withMode(CreateMode.EPHEMERAL).forPath(path);
		}
		Thread.sleep(1000);
		client.create().withMode(CreateMode.EPHEMERAL)
				.forPath(path + "/burton");
		synchronized (NodeCacheChildDemo.class) {
			while (true) {
				try {
					NodeCacheChildDemo.class.wait();
				} catch (InterruptedException e) {
				}
			}
		}
		// Thread.sleep(1000);
		// client.delete().forPath(path+"/burton");
		// Thread.sleep(1000);
		// client.delete().forPath(path);
		// Thread.sleep(Integer.MAX_VALUE);
	}

}
